﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.LanguageWire.LWIntegration;
using iLangl.Model;
using LW.DB;
using System.Data.SqlClient;
using System.Data;

namespace iLangl.LanguageWire.DAL.LanguageWireDAL.RealStorage
{
	public class ContactDAL : BaseStorageLWAPI, IContactDAL
	{
		public void CreateContact(Contact contact, bool isPrimary)
		{
			if (contact == null)
				return;


			if (!string.IsNullOrEmpty(contact.TPIdentity))
				return;

			CreateCustomerRequest createCustomerRequest = new CreateCustomerRequest();

			createCustomerRequest.AuthKey = LanguageWireConfiguration.Instance.AuthKey;
			createCustomerRequest.OriginId = LanguageWireConfiguration.Instance.CustomerOrigin;


			createCustomerRequest.MakePrimaryCustomer = isPrimary;
			createCustomerRequest.CompanyId = int.Parse(contact.Company.TPIdentity);

			if (contact.Company.BillingInfo != null)
				createCustomerRequest.PrimaryInvoicingAccountId = int.Parse(contact.Company.BillingInfo.TPIdentity);

			createCustomerRequest.Email = contact.Email;
			createCustomerRequest.LastName = contact.LastName;
			createCustomerRequest.FirstName = contact.FirstName;
			createCustomerRequest.CountryId = LanguageWireConfiguration.Instance.CountryId;

			ClientManagementServiceClient client = new ClientManagementServiceClient();
			int customerId = client.CreateCustomer(createCustomerRequest);

			iLangl.LanguageWire.DAL.iLanglDAL.DALFacade.Instance.ContactDAL.UpdateContactReference(contact.Id, customerId, null);
			contact.TPIdentity = customerId.ToString();
		}


		public Contact GetResponsiblePerson(int jobId)
		{
			DBProvider dbProvider = new DBProvider();

			SqlParameter[] parameters = new SqlParameter[]
				{
					new SqlParameter("@JobId", jobId),
				};

			Contact contact = null;
			using (SqlDataReader reader = dbProvider.ExecuteReader(
@"Select 
	a.ID,
	a.Name,
	a.Email,
	a.SMSPhone Phone,
	a.Title
	
from AdminContacts a
Join CustomerJobs cj on cj.AdminContactID = a.ID
where cj.JobID = @JobId",
				CommandType.Text, parameters))
			{
				if (reader.Read())
				{
					contact = new Contact();
					contact.Id = (String)reader["Id"];

					String fullName = (String)reader["Name"];
					string[] names = fullName.Split();

					if (names.Length > 0)
						contact.FirstName = names[0];

					if (names.Length > 1)
						contact.LastName = names[0];

					contact.TPIdentity = contact.Id;
					contact.Phone = (String)reader["Phone"];
					contact.Title = (String)reader["Title"];
					contact.Email = (String)reader["Email"];
				}
			}

			return contact;
			
		}
	}
}
